package io.renren.modules.member.controller;

import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.annotation.NoRepeatSubmit;
import io.renren.common.exception.RRException;
import io.renren.common.utils.*;
import io.renren.modules.member.entity.*;
import io.renren.modules.member.entity.vo.MemberVo;
import io.renren.modules.member.service.TStoreMemberAccountDetailService;
import io.renren.modules.member.service.TStoreMemberService;
import io.renren.modules.member.service.TStoreMemberTypeService;
import io.renren.modules.store.entity.TStoreStaffCommissionRecordEntity;
import io.renren.modules.store.entity.TStoreStaffCommissionTypeEntity;
import io.renren.modules.store.entity.TStoreTimeIntervalEntity;
import io.renren.modules.store.service.TStoreStaffCommissionRecordService;
import io.renren.modules.store.service.TStoreStaffCommissionTypeService;
import io.renren.modules.sys.controller.AbstractController;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


/**
 * 
 *
 * @author steakliu
 * @email 2319492349@qq.com
 * @date 2021-01-26 22:36:10
 */
@RestController
@RequestMapping("store/tstoremember")
public class TStoreMemberController extends AbstractController {
    @Autowired
    private TStoreMemberService tStoreMemberService;
    @Autowired
    private TStoreMemberTypeService tStoreMemberTypeService;
    @Autowired
    private TStoreStaffCommissionTypeService tStoreStaffCommissionTypeService;
    @Autowired
    private TStoreStaffCommissionRecordService recordService;
    @Autowired
    private TStoreMemberAccountDetailService accountDetailService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("store:tstoremember:list")
    public R list(@RequestParam Map<String, Object> params){
        params.put("status",params.get("status"));
        params.put("sellerId",getSeller());
        params.put("key",params.get("key"));
        PageUtils page = tStoreMemberService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/listMember")
    @RequiresPermissions("store:tstoremember:list")
    public R listMember(@RequestParam Map<String, Object> params){
        params.put("sellerId",getSeller());
        Page<MemberVo> page = tStoreMemberService.listMember(params);
        return R.ok().put("data",page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("store:tstoremember:info")
    public R info(@PathVariable("id") Long id){
		TStoreMemberEntity tStoreMember = tStoreMemberService.getById(id);
        TStoreMemberTypeEntity typeEntity = tStoreMemberTypeService.getById(tStoreMember.getMemberTypeId());
        tStoreMember.setMemberTypeName(typeEntity.getMemberTypeName());
        tStoreMember.setDiscount(typeEntity.getDefaultDiscount());
        //TODO 这里查看会员详情还要去查会员账户信息
        TStoreMemberAccountDetailEntity accountDetailEntity = accountDetailService.getById(id);
        tStoreMember.setIntegral(accountDetailEntity.getIntegral());
        tStoreMember.setTotalConsume(accountDetailEntity.getTotalConsume());
        tStoreMember.setBalace(accountDetailEntity.getBalace());
        return R.ok().put("tStoreMember", tStoreMember);
    }

    /**
     * 保存
     */
    @NoRepeatSubmit
    @RequestMapping("/save")
    @RequiresPermissions("store:tstoremember:save")
    @Transactional(rollbackFor = Exception.class)
    public R save(@RequestBody TStoreMemberEntity tStoreMember){
        TStoreMemberEntity one = tStoreMemberService.getOne(new QueryWrapper<TStoreMemberEntity>()
                .eq("seller_id", getSeller())
                .eq("id_card", tStoreMember.getIdCard())
        );
        if (!BeanJudgeUtil.beanIsNull(one)){
            throw new RRException("身份证已被注册，请检测是否办理过会员");
        }
        TStoreMemberEntity one1 = tStoreMemberService.getOne(new QueryWrapper<TStoreMemberEntity>()
                .eq("seller_id", getSeller())
                .eq("tel", tStoreMember.getTel())
        );
        if (!BeanJudgeUtil.beanIsNull(one1)){
            throw new RRException("电话已被注册，请检测是否办理过会员");
        }
        tStoreMember.setMemberCardNo(FastIDUtil.fastId());
        tStoreMember.setCreateUserId(getUserId());
        tStoreMember.setCreateTime(new Date());
        tStoreMember.setSellerId(getSeller());
        tStoreMember.setRegisterTime(new Date());
        //保存会员表
		tStoreMemberService.save(tStoreMember);

        //获取会员
        TStoreMemberEntity member = tStoreMemberService.getOne(
                new QueryWrapper<TStoreMemberEntity>()
                        .eq("id_card", tStoreMember.getIdCard())
                        .eq("seller_id",getSeller())
        );
        //获取办理会员卡所需要的金额
        TStoreMemberTypeEntity memberTypeEntity = tStoreMemberTypeService.getOne(
                new QueryWrapper<TStoreMemberTypeEntity>()
                        .eq("id", tStoreMember.getMemberTypeId())
        );

        //保存会员账户表
        TStoreMemberAccountDetailEntity accountDetailEntity = new TStoreMemberAccountDetailEntity();
        accountDetailEntity.setMemberId(member.getId());
        //如果办卡需要支付
        if (memberTypeEntity.getPayFlag() == 1){
            accountDetailEntity.setBalace(memberTypeEntity.getPayMoney());
            accountDetailEntity.setIntegral(memberTypeEntity.getInitialIntegral());
        }else {
            accountDetailEntity.setBalace(0.0);
            accountDetailEntity.setIntegral(0.0);
        }
        accountDetailEntity.setUpdateMan(getUserId());
        accountDetailEntity.setUpdateTime(new Date());
        accountDetailService.save(accountDetailEntity);

        //员工提成类型(如果选择了提成类型)
        TStoreStaffCommissionRecordEntity commissionRecordEntity = new TStoreStaffCommissionRecordEntity();
        if (tStoreMember.getCommissionTypeId() != null){
            TStoreStaffCommissionTypeEntity comType = tStoreStaffCommissionTypeService.getOne(
                    new QueryWrapper<TStoreStaffCommissionTypeEntity>()
                            .eq("seller_id", getSeller())
                            .eq("id", tStoreMember.getCommissionTypeId())
            );
            //计算员工提成金额
            double comMoney = memberTypeEntity.getPayMoney()*comType.getPercentage()/100;
            commissionRecordEntity.setCommissionMoney(comMoney);
        }else {
            commissionRecordEntity.setCommissionMoney(null);
        }
        commissionRecordEntity.setMemberId(member.getId());
        commissionRecordEntity.setCommissionNo(FastIDUtil.fastId());
        commissionRecordEntity.setSellerId(getSeller());
        commissionRecordEntity.setSaleTime(new Date());
        commissionRecordEntity.setCommissionTypeId(tStoreMember.getCommissionTypeId());
        commissionRecordEntity.setSaleMoney(memberTypeEntity.getPayMoney());
        //如果选择了销售员
        List<TStoreStaffCommissionRecordEntity> list = new ArrayList<>();
        if (tStoreMember.getSalemanList().size() > 0){
            for (Long staffId : tStoreMember.getSalemanList()){
                TStoreStaffCommissionRecordEntity recordEntity = new TStoreStaffCommissionRecordEntity();
                commissionRecordEntity.setStaffId(staffId);
                BeanUtil.copyProperties(commissionRecordEntity,recordEntity);
                list.add(recordEntity);
            }
            //保存员工提成记录表
            recordService.saveBatch(list);
        }else {
            commissionRecordEntity.setStaffId(null);
            recordService.save(commissionRecordEntity);
        }

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("store:tstoremember:update")
    public R update(@RequestBody TStoreMemberEntity tStoreMember){
		tStoreMemberService.updateById(tStoreMember);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("store:tstoremember:delete")
    public R delete(@RequestBody Long[] ids){
		tStoreMemberService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
